home *** CD-ROM | disk | FTP | other *** search
- Imports System.Reflection
-
- Module MainModule
-
- Sub Main()
- ' Run one of the Textxxxx procedures below by uncommenting only one statement
-
- 'TestAssembly()
- 'TestAssemblyEnumeration()
- 'TestAssemblyMethods()
- 'TestAssemblyName()
- 'TestModule()
- 'TestType()
- 'TestTypeEnumeration()
- 'TestMemberEnumeration()
- 'TestFindMembers()
- 'TestGetPropertyGetMethod()
- 'TestFilteredList()
- 'TestCallingSyntax()
- 'TestReadWriteFields()
- 'TestReadWriteProperties()
- 'TestReadWritePropertiesWithArgs()
- 'TestInvokeMethod()
- 'TestInvokeMember()
- 'TestObjectCreation()
- 'TestObjectCreation2()
- 'TestObjectCreation3()
- 'TestStackFrame()
- 'TestStackFrameFromException()
-
- ' You need these statements when running inside Visual Studio, so that
- ' the Console window doesn't disappear
- Console.WriteLine("")
- Console.WriteLine(">>> Press Enter to terminate the program <<<")
- Console.ReadLine()
- End Sub
-
- ' this procedure tests basic Assembly properties
-
- Sub TestAssembly()
- Dim asm As Reflection.Assembly ' Assumes Imports System.Reflection.
-
- ' Get a reference to the assembly this code is running into.
- asm = [Assembly].GetExecutingAssembly()
- Console.WriteLine("GetExecutingAssembly method: " & asm.FullName)
- Console.WriteLine("")
-
- ' Get a reference to an assembly given its file name.
- ' (Replace with an actual file name to avoid the error.)
- Try
- asm = Reflection.Assembly.LoadFrom("c:\myapp\mylib.dll")
- Console.WriteLine("LoadFrom method:" & asm.FullName)
- Catch ex As Exception
- Console.WriteLine("Unabble to find the assembly.")
- End Try
- Console.WriteLine("")
-
- ' Get a reference to the assembly that contains a given Type.
- ' (The argument must be a System.Type value, so we need GetType.)
- asm = Reflection.Assembly.GetAssembly(GetType(String))
- Console.WriteLine("GetAssembly(GetType(String)) method: " & asm.FullName)
- Console.WriteLine("")
-
- ' Get a reference to an assembly given its display name.
- asm = Reflection.Assembly.Load("mscorlib")
- Console.WriteLine("Load(""mscorlib"") method: " & asm.FullName)
- Console.WriteLine("")
-
- Console.WriteLine("Location = " & asm.Location)
- ' => C:/WINNT/Microsoft.NET/Framework/v1.0.3300/mscorlib.dll
- Console.WriteLine("CodeBase = " & asm.CodeBase)
- ' => file://C:/WINNT/Microsoft.NET/Framework/v1.0.3300/mscorlib.dll
- ' (The actual location can of course be different on your system.)
- Try
- Console.WriteLine("EntryPoint = " & asm.EntryPoint.Name)
- Catch ex As Exception
- Console.WriteLine(ex.message)
- End Try
- End Sub
-
- ' this procedure tests enumeration of modules and types
-
- Sub TestAssemblyEnumeration()
- Dim asm As [Assembly] = Reflection.Assembly.Load("mscorlib")
-
- ' Enumerate all the modules in an assembly.
- Console.WriteLine("Modules in the assembly")
- Dim mo As [Module]
- For Each mo In asm.GetModules
- Console.WriteLine(mo.FullyQualifiedName)
- Next
- Console.WriteLine("Press Enter to see all the types in the assembly")
- Console.ReadLine()
-
- ' Enumerate all the types defined in an assembly.
- Dim ty As Type
- For Each ty In asm.GetTypes
- Console.WriteLine(ty.FullName)
- Next
- Console.WriteLine("Press Enter to see all the exported types")
- Console.ReadLine()
-
- For Each ty In asm.GetExportedTypes
- Console.WriteLine(ty.FullName)
- Next
- Console.WriteLine("")
- End Sub
-
- ' this procedure test basic methods of the Assembly class
-
- Sub TestAssemblyMethods()
- Dim asm As [Assembly] = Reflection.Assembly.Load("mscorlib")
-
- ' Next statement assumes asm is pointing to MSCORLIB.
- Dim ty As Type = asm.GetType("System.Int32")
- Console.WriteLine(ty.FullName)
- Console.WriteLine("")
-
- ' this returns Nothing, because the type isn't defined
- ' (comparison is case-sensitive)
- ty = asm.GetType("system.int32")
- If ty Is Nothing Then
- Console.WriteLine("The GetType method returned Nothing")
- Else
- Console.WriteLine(ty.FullName)
- End If
- Console.WriteLine("")
-
- ' this raises an exception because the name is compared in case-insensitive way
- Try
- ty = asm.GetType("system.int32", True)
- Catch ex As Exception
- Console.WriteLine(ex.Message)
- End Try
- Console.WriteLine("")
-
- ' This doesn't raise any exception because type name
- ' is compared in case-insensitive way.
- ty = asm.GetType("system.int32", True, True)
- Console.WriteLine(ty.FullName) ' => System.Int32
- Console.WriteLine("")
-
- ' A long-winded way to create an Integer.
- Dim o As Object = asm.CreateInstance("System.Int32")
- ' Prove that we have created an Integer.
- Console.Write(o.GetType.FullName) ' => System.Int32
- End Sub
-
- ' this procedure tests the AssemblyName object
-
- Sub TestAssemblyName()
- ' Get a reference to an assembly and its AssemblyName.
- Dim asm As [Assembly] = Reflection.Assembly.Load("mscorlib")
- Dim an As AssemblyName = asm.GetName
-
- ' (Of course you can get different output on your system, depending
- ' on the runtime versions you've installed and system paths.)
- Console.WriteLine(an.CodeBase)
- ' => file://C:/WINNT/Microsoft.NET/Framework/v1.0.3300/mscorlib.dll
- Console.WriteLine(an.FullName)
- ' => mscorlib, Version=1.0.2411.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
-
- ' These properties come from the Version dependent object.
- Console.WriteLine(an.Version.Major) ' => 1
- Console.WriteLine(an.Version.Minor) ' => 0
- Console.WriteLine(an.Version.Build) ' => 2204
- Console.WriteLine(an.Version.Revision) ' => 21
- ' You can also get the version as a single number.
- Console.WriteLine(an.Version.ToString) ' => 1.0.21.2204
- Console.WriteLine("")
-
- ' Display the hash code of the assembly as a comma-delimited
- ' list of bytes.
- Console.Write("PublicKey of mscorlib: ")
- Dim b As Byte
- For Each b In an.GetPublicKeyToken()
- Console.Write(b.ToString & ",")
- Next
- Console.WriteLine("")
-
- ' Get information on all the assemblies the current assembly references.
- Dim anArr() As AssemblyName
- anArr = [Assembly].GetExecutingAssembly.GetReferencedAssemblies()
- Console.WriteLine("Assemblies referenced by the running assembly:")
- For Each an In anArr
- Console.WriteLine(an.FullName)
- Next
- Console.WriteLine("")
-
- ' check whether the assembly can run side-by-side
- Dim avc As System.Configuration.Assemblies.AssemblyVersionCompatibility
- avc = an.VersionCompatibility
- If (avc And Configuration.Assemblies.AssemblyVersionCompatibility. _
- SameMachine) <> 0 Then
- Console.WriteLine("The assembly can run side-by-side with other versions of " _
- & "this assembly running on the same machine")
- End If
- End Sub
-
- ' this procedure tests the Module object
-
- Sub TestModule()
- Dim asm As [Assembly] = Reflection.Assembly.Load("mscorlib")
- Dim mo As [Module]
-
- For Each mo In asm.GetModules
- Console.WriteLine(mo.Name & " รป " & mo.ScopeName)
- ' => mscorlib.dll - CommonLanguageRuntimeLibrary
- Next
-
- ' get a reference to the only module in mscorlib.dll.
- mo = asm.GetModule("CommonLanguageRuntimeLibrary")
- Console.WriteLine(mo.FullyQualifiedName)
- ' => c:\winnt\microsoft.net\framework\v1.0.2914\mscorlib.dll
- End Sub
-
- ' this procedure tests the System.Type object
-
- Sub TestType()
- ' get a Type object using VB's GetType function
- Dim ty As Type = GetType(String)
- Console.WriteLine(ty.FullName) ' => System.String
-
- ' get a Type using the GetType method(inherited from System.Object)
- Dim d As Double
- ty = d.GetType
- Console.WriteLine(ty.FullName) ' => System.Double
-
- ' get a Type using the Type.GetType shared method
- ty = Type.GetType("System.Int64")
- Console.WriteLine(ty.FullName) ' => System.Int64
- Console.WriteLine()
- '
- ' Get the type buried in an assembly.
- ty = Type.GetType("System.Data.DataSet, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
- ' NOTE: the above statement fails under a different version of the runtime.
- ' Here's how you can make it succeed always
- Dim asm As [Assembly] = [Assembly].LoadWithPartialName("System.Data")
- ty = Type.GetType("System.Data.DataSet, " & asm.FullName)
-
- ' Test the AssemblyQualifiedName
- Console.WriteLine(GetType(String).AssemblyQualifiedName)
- Console.WriteLine("")
-
- ' get the types for an array of objects.
- Dim anArray() As Object = {"a string", 123%, #1/2/2001#}
- Dim types() As Type = Type.GetTypeArray(anArray)
- Console.WriteLine(types(0).FullName) ' => System.String
- Console.WriteLine(types(1).FullName) ' => System.Int32
- Console.WriteLine(types(2).FullName) ' => System.DateTime
- Console.WriteLine()
-
- ' Get the .NET object that wraps the Word.Application component.
- Dim wordtype As Type = Type.GetTypeFromProgID("Word.Application")
- ' Display information on the wrapping object.
- Console.WriteLine(wordtype.Name) ' => __ComObject
- ' This is the CLSID value stored in the registry.
- Console.WriteLine(wordtype.GUID) ' => 000209ff-0000-0000-c000-000000000046
- ' Get a reference through the CLSID.
- Dim type2 As Type = Type.GetTypeFromCLSID(wordtype.GUID)
- ' Prove that this is the same object.
- Console.WriteLine(wordtype Is type2) ' => True
- End Sub
-
- ' this procedure enumerates all the types in mscorlib.dll
-
- Sub TestTypeEnumeration()
- Dim asm As [Assembly] = Reflection.Assembly.Load("mscorlib")
- Dim t As Type
-
- For Each t In asm.GetExportedTypes()
- If t.IsClass Then
- Console.WriteLine(t.Name & " (Class)")
- ElseIf t.IsEnum Then
- ' Note that an enum is also a value type, so we must
- ' test for IsEnum before IsValueType.
- Console.WriteLine(t.Name & " (Enum)")
- ElseIf t.IsValueType Then
- Console.WriteLine(t.Name & " (ValueType)")
- ElseIf t.IsInterface Then
- Console.WriteLine(t.Name & " (Interface)")
- Else
- ' This statements is never reached, because a type
- ' can't be something other than one of the above.
- End If
- Next
- End Sub
-
- ' this procedure tests member enumeration
-
- Sub TestMemberEnumeration()
- ' Get a reference to the System.String type.
- Dim stringType As Type = Type.GetType("System.String")
- Dim minfos() As MemberInfo
- Dim mi As MemberInfo
-
- ' List all its members.
- Console.WriteLine("All members of the System.String class:")
- minfos = stringType.GetMembers()
- For Each mi In minfos
- Console.WriteLine(mi.Name)
- Next
- Console.WriteLine()
-
- ' Get all public, non-shared, non-inherited members of System.String.
- Console.WriteLine("Press Enter to see all public, non-shared, non-inherited members of the System.String class:")
- Console.ReadLine()
- minfos = stringType.GetMembers(BindingFlags.Public _
- Or BindingFlags.Instance Or BindingFlags.DeclaredOnly)
- For Each mi In minfos
- Console.WriteLine(mi.Name)
- Next
- Console.WriteLine()
-
- ' Get all the methods of System.String.
- Console.WriteLine("Press Enter to see all the methods of the System.String class:")
- Console.ReadLine()
- For Each mi In GetType(String).GetMethods()
- Console.WriteLine(mi.Name)
- Next
- Console.WriteLine()
-
- ' Get all the interfaces of System.String.
- Console.WriteLine("Press Enter to see all the interfaces of the System.String class:")
- Console.ReadLine()
- Dim ty As Type
- For Each ty In stringType.GetInterfaces()
- Console.WriteLine(ty.Name)
- Next
- End Sub
-
- ' this procedure tests the FindMembers method
-
- Sub TestFindMembers()
- ' Get a reference to the System.String type.
- Dim stringType As Type = Type.GetType("System.String")
- Dim minfos() As MemberInfo
- Dim mi As MemberInfo
-
- ' Get only public, instance methods and properties
- ' whose name begins with "C".
- minfos = stringType.FindMembers( _
- MemberTypes.Method Or MemberTypes.Property, _
- BindingFlags.Public Or BindingFlags.Instance, _
- AddressOf FilterByName, "C")
-
- ' List the results.
- Console.WriteLine("Methods and Properties of System.String whose name starts with 'C'")
- For Each mi In minfos
- Console.WriteLine(mi.Name)
- Next
- Console.WriteLine()
-
- ' We're looking for properties and functions that return a 32-bit integer.
- Dim returnType As Type = Type.GetType("System.Int32")
- ' We're searching only public, non-shared methods and properties.
- minfos = stringType.FindMembers( _
- MemberTypes.Method Or MemberTypes.Property, _
- BindingFlags.Public Or BindingFlags.Instance, _
- AddressOf FilterByType, returnType)
-
- Console.WriteLine("Press Enter to see properties and methods that return an Integer value:")
- Console.ReadLine()
- For Each mi In minfos
- Console.WriteLine(mi.Name)
- Next
- Console.WriteLine()
- End Sub
-
- ' This filtering function returns True if the member name
- ' begins with the character passed as its second argument.
- Function FilterByName(ByVal m As MemberInfo, _
- ByVal filterCriteria As Object) As Boolean
- If m.Name.StartsWith(filterCriteria.ToString) Then
- Return True
- End If
- End Function
-
- ' Accept only properties and methods whose return value matches
- ' the Type passed as the second argument.
- Function FilterByType(ByVal m As MemberInfo, _
- ByVal filterCriteria As Object) As Boolean
-
- If m.MemberType = MemberTypes.Property Then
- ' If it is a property, cast MemberInfo to PropertyInfo.
- Dim pi As PropertyInfo = CType(m, PropertyInfo)
- ' Return True if the property type is the one we're looking for.
- Return (pi.PropertyType Is filterCriteria)
- ElseIf m.MemberType = MemberTypes.Method Then
- ' If it is a method, cast MemberInfo to MethodInfo.
- Dim mi As MethodInfo = CType(m, MethodInfo)
- ' Return True if the return type is the one we're looking for.
- Return (mi.ReturnType Is filterCriteria)
- End If
- End Function
-
- ' this procedure tests the GetProperty and GetMethod methods
-
- Sub TestGetPropertyGetMethod()
- ' Test whether the Chars property is read-only.
- Dim pi As PropertyInfo = GetType(String).GetProperty("Chars")
- If pi.CanWrite Then
- Console.WriteLine("The Chars property is writeable")
- Else
- Console.WriteLine("The Chars property is read-only")
- End If
- Console.WriteLine()
-
- ' Get the MethodInfo object for the IndexOf string method with the
- ' following signature: IndexOf(char, startIndex, endIndex).
-
- ' Prepare the signature as an array of Type objects.
- ' Note that you can define the type of arguments using either
- ' the GetType function or the Type.GetType method.
- Dim argTypes() As Type = {GetType(Char), _
- Type.GetType("System.Int32"), Type.GetType("System.Int32")}
- ' Ask for the method with given name and signature.
- Dim mi As MethodInfo = GetType(String).GetMethod("IndexOf", argTypes)
- Console.WriteLine("The IndexOf(Char, Integer, Integer) returns the following type: " & mi.ReturnType.FullName)
- End Sub
-
- ' this procedure shows how to filter member lists
-
- Sub TestFilteredList()
- ' Get a reference to the System.String type.
- Dim stringType As Type = Type.GetType("System.String")
- ' We use this ArrayList to keep track of items already displayed.
- Dim al As New ArrayList()
-
- Dim mi As MemberInfo
- For Each mi In stringType.GetMembers()
- If (mi.MemberType And MemberTypes.Constructor) <> 0 Then
- ' Ignore constructor methods.
- ElseIf Not al.Contains(mi.Name) Then
- ' If this element hasn't been listed yet, do it now.
- ' (The MemberType property returns an enumerated value, thus we can
- ' transform it into its textual description with the ToString method.)
- Console.WriteLine("{0} ({1})", mi.Name, mi.MemberType.ToString)
- ' Add this element to the list of processed items.
- al.Add(mi.Name)
- End If
- Next
- End Sub
-
- ' this procedure tests how to display the parameter signature of a method
-
- Sub TestCallingSyntax()
- ' Get a reference to the System.String type.
- Dim stringType As Type = Type.GetType("System.String")
- ' Get the MethodInfo for the CopyTo method.
- Dim mi As MethodInfo = stringType.GetMethod("CopyTo")
- ' Get the ParameterInfo array for this method.
- Dim pinfos() As ParameterInfo = mi.GetParameters
- Dim i As Integer
-
- ' Display the calling syntax for this method.
- Console.Write(mi.Name & "(")
- For i = 0 To pinfos.GetUpperBound(0)
- ' Display the parameter name.
- Console.Write(pinfos(i).Name)
- ' If not the last parameter, append a comma.
- If i < pinfos.GetUpperBound(0) Then Console.Write(",")
- Next
- ' Display the closing parenthesis.
- Console.WriteLine(")")
- End Sub
-
- ' this procedure reads and writes fields
-
- Sub TestReadWriteFields()
- ' Create a Person object.
- Dim p As New Person("Joe", "Doe")
- ' Reflect on it.
- Dim ty As Type = p.GetType
- ' Get a reference to its FirstName Field.
- Dim fi As FieldInfo = ty.GetField("FirstName")
- ' Display its current value.
- Console.WriteLine(fi.GetValue(p)) ' => Joe
- ' Change it.
- fi.SetValue(p, "Robert")
- ' Prove that it changed.
- Console.WriteLine(p.FirstName) ' => Robert
- End Sub
-
- ' this procedure tests reading and writing parameterless properties
-
- Sub TestReadWriteProperties()
- ' Get a Person object and reflect on it.
- Dim p As New Person("Joe", "Doe")
- Dim ty As Type = p.GetType
- ' Set the Age property.
- Dim pi As PropertyInfo = ty.GetProperty("Age")
- ' Note that the type of value must match exactly.
- ' (Integer constants must be converted to Short, in this case.)
- pi.SetValue(p, 35S, Nothing)
- ' Read it back.
- Console.WriteLine(pi.GetValue(p, Nothing)) ' => 35
- End Sub
-
- ' this procedure tests reading and writing properties with arguments
-
- Sub TestReadWritePropertiesWithArgs()
- ' Get a Person object and reflect on it.
- Dim p As New Person("Joe", "Doe")
- Dim ty As Type = p.GetType
- ' Get a reference to the PropertyInfo object
- Dim pi As PropertyInfo = ty.GetProperty("EmailAddress")
- ' Prepare the array of parameters.
- Dim params() As Object = {1S}
- ' Set the property.
- pi.SetValue(p, "321 North Street", params)
- ' Read it back.
- Console.WriteLine(pi.GetValue(p, params)) ' => 321 North Street
- End Sub
-
- ' this procedure tests invoking a method
-
- Sub TestInvokeMethod()
- ' Get a Person object and reflect on it.
- Dim p As New Person("Joe", "Doe")
- Dim ty As Type = p.GetType
- ' Get the MethodInfo for this method.
- Dim mi As MethodInfo = ty.GetMethod("SendEmail")
- ' Prepare an array for arguments with same number of expected parameters.
- Dim params(mi.GetParameters.Length - 1) As Object
- ' Set parameters values.
- params(0) = "This is a message"
- params(1) = 3
- ' Invoke the method.
- mi.Invoke(p, params)
- Console.WriteLine()
-
- ' try again, but omit the Optional argument
- params(0) = "This is another message"
- params(1) = Type.Missing
- mi.Invoke(p, params)
- Console.WriteLine()
-
- ' try once again, but use a different technique
- ' Retrieve the DefaultValue from the ParameterInfo object.
- params(0) = "This is yet another message"
- params(1) = mi.GetParameters(1).DefaultValue
- mi.Invoke(p, params)
- End Sub
-
- ' test the InvokeMember method
-
- Sub TestInvokeMember()
- ' Create a Person object and get its corresponding Type object.
- Dim p As New Person()
- Dim ty As Type = p.GetType
-
- ' Set the FirstName field.
- Dim args() As Object = {"Francesco"} ' One argument.
- ty.InvokeMember("FirstName", BindingFlags.SetField, Nothing, p, args)
- Console.WriteLine("Set FirstName property through InvokeMember")
-
- ' Read the FirstName field.
- ' (Note that we're passing Nothing for the argument array.)
- Dim value As Object = ty.InvokeMember("FirstName", BindingFlags.GetField, _
- Nothing, p, Nothing)
- Console.WriteLine("FirstName is now {0}", value)
-
- ' Set the Age property.
- Dim args2() As Object = {35S} ' One argument.
- ty.InvokeMember("Age", BindingFlags.SetProperty, Nothing, p, args2)
- Console.WriteLine("Age is now {0}", p.Age)
-
- ' Call the SendEMail method.
- Dim args3() As Object = {"This is a message", 2}
- ty.InvokeMember("SendEmail", BindingFlags.InvokeMethod, Nothing, p, args3)
- End Sub
-
- ' this procedure tests object creation using default constructor
-
- Sub TestObjectCreation()
- ' Next statement assumes that the Person class is defined in
- ' an assembly named "ReflectionDemo".
- Dim ty As Type = Type.GetType("ReflectionDemo.Person")
- Dim o As Object = Activator.CreateInstance(ty)
- ' prove that we created a Person
- Console.WriteLine("A {0} object has been created", o.GetType.Name)
- End Sub
-
- ' this procedure tests object creator using a constructor that takes arguments
-
- Sub TestObjectCreation2()
- Dim ty As Type = Type.GetType("ReflectionDemo.Person")
- ' Use the constructor that takes two arguments.
- Dim params() As Object = {"Joe", "Doe"}
- ' Call the constructor that matches the parameter signature.
- Dim o As Object = System.Activator.CreateInstance(ty, params)
- ' prove that we created a Person and that arguments were passed correctly
- Console.WriteLine("A {0} object has been created", o.GetType.Name)
- Dim p As Person = CType(o, Person)
- Console.WriteLine("FirstName = {0}, LastName = {1}", p.FirstName, p.LastName)
- End Sub
-
- ' this procedure tests object creation by explicitly calling the constructor
-
- Sub TestObjectCreation3()
- Dim ty As Type = Type.GetType("ReflectionDemo.Person")
- ' Prepare the argument signature as an array of types (2 strings).
- Dim types() As Type = {GetType(System.String), GetType(System.String)}
- ' Get a reference to the correct constructor.
- Dim ci As ConstructorInfo = ty.GetConstructor(types)
- ' Prepare the parameters.
- Dim params() As Object = {"Joe", "Doe"}
- ' Invoke the constructor and assign the result to a variable.
- Dim o As Object = ci.Invoke(params)
- ' prove that we created a Person and that arguments were passed correctly
- Console.WriteLine("A {0} object has been created", o.GetType.Name)
- Dim p As Person = CType(o, Person)
- Console.WriteLine("FirstName = {0}, LastName = {1}", p.FirstName, p.LastName)
- End Sub
-
- ' this procedure tests the StackFrame object
-
- Sub TestStackFrame()
- ' call an inner procedure
- TestStackFrame_1()
- End Sub
-
- Sub TestStackFrame_1()
- TestStackFrame_2()
- End Sub
-
- Sub TestStackFrame_2()
- Dim i As Integer
- Dim st As New System.Diagnostics.StackTrace()
- ' Enumerate all the stack frame objects.
- ' (0-th frame corresponds to the current routine.)
- For i = 0 To st.FrameCount - 1
- ' Get the I-th stack frame and print the method name.
- Dim sf As System.Diagnostics.StackFrame = st.GetFrame(i)
- Console.WriteLine(sf.GetMethod.Name)
- Next
- End Sub
-
- ' this procedure tests the StackFrame from an Exception
-
- Sub TestStackFrameFromException()
- Try
- ' This causes an exception.
- TestStackFrameFromException_1(1)
- Catch e As Exception
- DisplayExceptionInfo(e)
- End Try
- End Sub
-
- Sub TestStackFrameFromException_1(ByVal x As Integer)
- TestStackFrameFromException_2("abc")
- End Sub
-
- Function TestStackFrameFromException_2(ByVal x As String) As String
- TestStackFrameFromException_3()
- End Function
-
- Sub TestStackFrameFromException_3()
- ' Cause an exception (null reference).
- Dim o As Object
- Console.Write(o.ToString)
- End Sub
-
- ' A reusable routine that displays error information
- Sub DisplayExceptionInfo(ByVal e As Exception)
- ' Display the error message.
- Console.WriteLine(e.Message)
-
- Dim st As New StackTrace(e, True)
- Dim i As Integer
-
- For i = 0 To st.FrameCount - 1
- ' Get the i-th stack frame.
- Dim sf As StackFrame = st.GetFrame(i)
- ' Get the corresponding method for that stack frame.
- Dim mi As MemberInfo = sf.GetMethod
- ' Get the namespace where that method is defined.
- Dim res As String = mi.DeclaringType.Namespace & "."
- ' Append the type name.
- res &= mi.DeclaringType.Name & "."
- ' Append the name of the method.
- res &= mi.Name
- ' Append information about the position in source file
- ' (but only if Debug information is available).
- If sf.GetFileName <> "" Then
- res &= " (" & sf.GetFileName & ", Line " & sf.GetFileLineNumber _
- & ", Col " & sf.GetFileColumnNumber
- End If
- ' Append information about offset in MSIL code, if available.
- If sf.GetILOffset <> StackFrame.OFFSET_UNKNOWN Then
- res &= ", IL offset " & sf.GetILOffset.ToString
- End If
- ' Append information about offset in native code.
- res &= ", native offset " & sf.GetNativeOffset & ")"
-
- Console.WriteLine(res)
- Next
- End Sub
-
- End Module
-
-